package com.bbc.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class CookiesUtils {

	public static void createCookies(HttpServletResponse reponse, String key, String value, int time, String path) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(path);
		cookie.setMaxAge(time);
		reponse.addCookie(cookie);
	}

	public static void createCookies(HttpServletRequest request, HttpServletResponse reponse, String key, String value, int time) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(request.getContextPath() + "/");
		cookie.setMaxAge(time);
		reponse.addCookie(cookie);
	}

	public static void createCookies(HttpServletRequest request, HttpServletResponse reponse, String key, String value,
			int time, boolean chinese) {
		if (key == null || value == null)
			return;
		try {
			Cookie cookie = new Cookie(URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value, "UTF-8"));
			cookie.setPath(request.getContextPath() + "/");
			cookie.setMaxAge(time);
			reponse.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static String getCookiesByKey(HttpServletRequest request, String key, boolean chinese) {
		if (key == null)
			return null;
		Cookie[] cs = request.getCookies();
		try {
			if (cs != null) {
				for (Cookie c : cs) {
					if (c.getName().equals(URLDecoder.decode(key, "UTF-8"))) {
						return URLDecoder.decode(c.getValue(), "UTF-8");
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;

	}

	public static String getCookiesByKey(HttpServletRequest request, String key) {
		Cookie[] cs = request.getCookies();
		if (cs != null) {
			for (Cookie c : cs) {
				if (c.getName().equals(key)) {
					return c.getValue();
				}
			}
		}
		return null;
	}

	public static void clear(HttpServletResponse reponse, String key, String path) {
		Cookie cookie = new Cookie(key, "");
		cookie.setPath(path);
		cookie.setMaxAge(-1);
		reponse.addCookie(cookie);
	}

	public static void clear(HttpServletRequest request, HttpServletResponse reponse, String key) {
		Cookie cookie = new Cookie(key, "");
		cookie.setPath(request.getContextPath() + "/");
		cookie.setMaxAge(-1);
		reponse.addCookie(cookie);
	}
}
